#ifndef EVM_HTTP_SERVER_H
#define EVM_HTTP_SERVER_H

#include <cstdint>
#include <string>
#include <vector>
#include <future>
#include <chrono>

#include "routing.h"
#include "timer_queue.h"
#include "event/tcp.h"



namespace evm {
    namespace common {
        class ThreadPool;
    }

    namespace http {

        using namespace std;
        using namespace event;

        struct DateStr {
            DateStr() {
                update_str();
            }

            string operator()() {
                auto now = chrono::steady_clock::now();
                if (now - last_ >= chrono::seconds(1)) {
                    last_ = now;
                    update_str();
                }
                return string(str_);
            }

        private:
            static constexpr int MAX_LENGTH = 100;

            void update_str() {
                auto t = ::time(0);
                tm m;
                gmtime_r(&t, &m);
                strftime(str_, MAX_LENGTH - 1, "%a, %d %b %Y %H:%M:%S GMT", &m);
            };

            chrono::steady_clock::time_point last_ = chrono::steady_clock::now();
            char str_[MAX_LENGTH];
        };

        struct HTTPServer : TCPServer {
            HTTPServer(const string &host, uint16_t port, size_t concurrency, EventLoop* loop = nullptr);

            ~HTTPServer();

            Router &router() {
                return router_;
            }

            void start();

            void stop();

            void handle(Request& request, Response& response);

            string server_name = "Evm Http Server";

        private:
            common::ThreadPool *pool_;
            TimerQueue timer_queue_;
            DateStr date_str_;

            Router router_;

            friend class HTTPConnection;
        };

    }
}

#endif //EVM_HTTP_SERVER_H
